<template>
  <el-card class="permissions-page">
    <div class="header">
      <div class="search">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item>
            <el-input
              v-model="formInline.title"
              placeholder="根据用户名搜索"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="formInline.title = ''">清空</el-button>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="add">
        <el-button type="success" class="el-icon-edit" @click="add"
          >新增权限组</el-button
        >
      </div>
    </div>
    <el-alert
      :title="`共${counts}条记录`"
      type="info"
      show-icon
      :closable="false"
    >
    </el-alert>
    <el-table
      :header-cell-style="{ background: '#FAFAFA' }"
      :data="permissionsData"
      style="width: 100%; margin-top: 20px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>

      <el-table-column prop="title" label="用户名"> </el-table-column>
      <el-table-column
        prop="create_date"
        label="日期"
        sortable
        :formatter="dateFormat"
      >
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            circle
            plain
            type="primary"
            icon="el-icon-edit"
            @click="edit(scope.row)"
          ></el-button>
          <el-button
            circle
            plain
            type="danger"
            icon="el-icon-delete"
            @click="del(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next,sizes,jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="params.page"
        :page-sizes="[10, 20, 30, 50]"
        :total="counts"
      >
      </el-pagination>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <div v-if="isAdd">
        <el-form
          ref="formRef"
          :model="permissionsForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="title">
            <el-input v-model="permissionsForm.title"></el-input>
          </el-form-item>
          <el-form-item label="权限分配">
            <el-tree
              :data="assignmentData"
              show-checkbox
              node-key="id"
              :props="defaultProps"
              @check="clickDeal"
            >
            </el-tree>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="isEdit">
        <el-form
          ref="formRef"
          :model="permissionsForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="title">
            <el-input v-model="permissionsForm.title"></el-input>
          </el-form-item>
          <el-form-item label="权限分配">
            <el-tree
            :default-checked-keys="defkeys"
            default-expand-all
              :data="assignmentData"
              show-checkbox
              node-key="id"
              :props="defaultProps"

  @check="clickDeal"
            >
            </el-tree>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { list, add, detail, update, remove } from '@/api/base/permissions'
import { menusList } from '@/api/base/menus'
export default {
  data () {
    return {
      formInline: {
        title: ''
      },
      params: {
        page: 1,
        pagesize: 10,
        title: ''
      },
      permissionsForm: {
        title: '',
        permissions: []
      },
      permissionsData: [],
      assignmentData: [],
      defaultProps: {
        children: 'childs',
        label: 'title'
      },
      multipleSelection: [],
      counts: null,

      dialogVisible: false,
      title: '',
      isAdd: false,
      isEdit: false,
      permissionOption: [],
      defkeys: [],
      rules: {
        title: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        email: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.list()
    this.menusList()
  },
  methods: {
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    dateFormat (row) {
      return this.$dayjs(row.addDate).format('YYYY-MM-DD')
    },
    onSubmit () {
      this.params.title = this.formInline.title

      this.list()
    },
    async list () {
      const { data } = await list(this.params)

      this.permissionsData = data.list
      this.counts = data.counts
    },
    async menusList () {
      const { data } = await menusList()

      const Array = JSON.parse(
        JSON.stringify(data).replace(/points/g, 'childs')
      )

      // 为其添加一个父节点
      const result = {
        id: 1,
        title: '系统菜单和页面权限点',
        childs: [...Array]
      }
      this.assignmentData.push(result)
      // push操作在每次点击添加的时候都会执行,会造成重复渲染的问题.解决:每次点击之前将树形图的数据来源置空
      // this.treeData = data
    },
    handleSizeChange (val) {
      this.params.pagesize = val
      this.list()
    },
    handleCurrentChange (current) {
      this.params.page = current
      this.list()
    },
    add () {
      this.title = '创建权限组'
      this.dialogVisible = true
      this.isAdd = true
      this.isEdit = false
    },

    clickDeal (currentObj, treeStatus) {
      this.permissionsForm.permissions = treeStatus.checkedKeys
    },
    async edit (row) {
      this.title = '编辑权限组'
      this.dialogVisible = true
      this.isAdd = false
      this.isEdit = true
      const { data } = await detail({ id: row.id })

      this.defkeys = data.permissions
      this.permissionsForm.title = data.title
      this.permissionsForm.id = data.id
      this.permissionsForm.permissions = this.defkeys
    },
    async save () {
      try {
        if (this.title === '创建权限组') {
          await this.$refs.formRef.validate()
          const res = await add(this.permissionsForm)

          if (res.status === 200) {
            this.$message.success('添加成功')
          } else {
            this.$message.error('添加失败')
          }
        } else {
          const res = await update(this.permissionsForm)
          if (res.status === 200) {
            this.$message.success('修改成功')
          } else {
            this.$message.error('修改失败')
          }
        }
        this.dialogVisible = false
        this.list()
      } catch (err) {
        this.$message.error(err.response.data)
      }
    },
    async del (row) {
      await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await remove(row)
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
      this.list()
    }
  }
}
</script>

<style scoped lang="scss">
.permissions-page {
  margin: 20px 20px;
  .header {
    display: flex;
    justify-content: space-between;
  }
  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  .el-dialog {
    .dialog-footer {
      display: block;
      text-align: center;
    }
  }
}
</style>
